# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/6/18

library(plyr)
library(gridExtra)
library(ggpubr)
library(egg)
library(lemon)
library(optparse)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--sc", default = "sample_color.txt", type = "character", help = "sample color file"),
  make_option("--mc", default = "meta_color.txt", type = "character", help = "metabolite color file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)


sampleIds <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote")) %>%
  .$SampleID

data <- read_csv(opt$i) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  select(c("Metabolite", sampleIds)) %>%
  rowwise() %>%
  do({
    result <- as_tibble(.)
    data <- result %>% select(-"Metabolite") %>% unlist()
    var <- var(data)
    if (var == 0 ) {
      result %>% filter(FALSE)
    }else result
  }) %>%
  ungroup() %>%
  mutate(Metabolite = factor(Metabolite, levels = unique(Metabolite))) %>%
  gather("SampleID", "Value", -Metabolite, factor_key = T) %>%
  spread(Metabolite, "Value") %>%
  mutate_at(vars(-"SampleID"), scale) %>%
  mutate_at(vars(-"SampleID"), function(x) {
    x1 <- x %>%
      unlist()
    return(x1)
  }) %>%
  arrange(factor(SampleID, levels = sampleIds)) %>%
  column_to_rownames("SampleID")

parent <- "./"
fileName <- paste0(parent, "/Z_Score.csv")

head(data)

write.csv(data, fileName)

